package handle

import (
	utilx "protocx/entity"

	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/context"
)

type Req struct {
}

func (r Req) InitRoute(party iris.Party) {
	p := party.Party("/req")
	p.Post("/post", r.PostValue())
	p.Post("/urlParam", r.URLParamDefault())
	p.Post("/params/{name}", r.Params())
	p.Post("/query", r.ReadQuery())
	p.Post("/readBody", r.ReadBody())
}
func (r Req) PostValue() iris.Handler {
	return func(context *context.Context) {
		context.JSON(context.PostValue("name"))
	}
}
func (r Req) URLParamDefault() iris.Handler {
	return func(context *context.Context) {
		context.JSON(context.URLParamDefault("name", "URLParamDefault"))
	}
}

// However, this one will match /user/john/ and also /user/john/send
// "/user/{name}/{action:path}",
func (r Req) Params() iris.Handler {
	return func(context *context.Context) {
		params := context.Params().Get("name")
		context.JSON(params)
	}
}

// ============

func (r Req) ReadQuery() iris.Handler {
	return func(ctx *context.Context) {
		var person utilx.Person
		if err := ctx.ReadQuery(&person); err != nil {
			ctx.StopWithError(iris.StatusBadRequest, err)
			return
		}

		ctx.Application().Logger().Infof("Person: %#+v", person)
		ctx.JSON(person)
	}
}
func (r Req) ReadBody() iris.Handler {
	return func(ctx *context.Context) {
		var person utilx.PersonAll
		if err := ctx.ReadBody(&person); err != nil {
			ctx.StopWithError(iris.StatusBadRequest, err)
			return
		}

		ctx.Application().Logger().Infof("Person: %#+v", person)
		ctx.JSON(person)
	}
}
